﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ExtendedDal;
using WMS.HelperClasses;
using WHMS.HelperClasses;
using WHMS.EntityClasses;
using SD.LLBLGen.Pro.ORMSupportClasses;
using WHMS;

namespace WMS
{
    public partial class AddGeneralItemsForm : Form
    {
        SupplyOrderEntity _currentSupplyOrder;
        TransactionEntity _currentTransaction;
        DepositTransactionEntity _currentDepositTransaction;
        DataMngrFormBase<SupplyOrderItemEntity> _tranItemsForm;
        List<ErrorProvider> _errorProviders;

        public AddGeneralItemsForm()
        {
            InitializeComponent();
            HideOrViewWeightCol();
            this._supplyOrderItems.EntityFactoryToUse = new WHMS.FactoryClasses.SupplyOrderItemEntityFactory();
        }

        private void HideOrViewWeightCol()
        {
            var weightCol = _transItemsGrid.Columns["Weight"];

            if (weightCol != null)
            {
                if (UserInfo.Roles.Where(r => r.ViewWorkshop == true).Count() > 0)
                {
                    weightCol.Visible = true;
                }
                else
                {
                    weightCol.Visible = false;
                }
            }
        }

        private void AddItemsForm_Load(object sender, EventArgs e)
        {
            LoadData();

            _errorProviders = new List<ErrorProvider>();

            InitializeDataSources();
        }
        private void NewBtn_Click(object sender, EventArgs e)
        {
            //InitializeDataSources();
            //ResetTransactionItems();
            ResetForm();

            if (!String.IsNullOrEmpty(txtExamineDocSerial.Text))
                PopulteExaminOrder(txtExamineDocSerial.Text);
            
        }
        private void SaveBtn_Click(object sender, EventArgs e)
        {
            Save();

            SyncSupplyItemsWithExamineItems();
        }

        private void Save()
        {
            if (!ValidateForm(true))
                return;

            if (!_currentTransaction.IsNew)
            {
                if ((bool)DALHelper.GetValue(DepositTransactionFields.IsPriced, DepositTransactionFields.Id, _currentDepositTransaction.Id))
                {
                    RetrieveTransaction();
                    return;
                }
            }

            var transItems = new EntityCollection<TransactionItemEntity>();
            var transItemsToDelete = new EntityCollection<TransactionItemEntity>();

            if (_currentDepositTransaction.IsNew)
            {
                _currentDepositTransaction.SupplierId = _currentSupplyOrder.SupplierId;
                _currentDepositTransaction.SupplyOrderNumber = _currentSupplyOrder.SupplyOrderNumber;

                var transaction = new TransactionEntity()
                {
                    ProjectId = _currentSupplyOrder.ProjectId,
                    StoreId = GetSelectedStoreId(),
                    PermitNumber = PermitNumberTB.Text,
                    CreatedBy = UserInfo.UserId,
                    Date = AdditionDateDTP.Value.Date,
                    Type = "Deposit"
                };

                _currentDepositTransaction.Transaction = transaction;
            }
            else
            {
                DALHelper.FetchCollection(transItems, new RelationPredicateBucket(TransactionItemFields.TransactionId == _currentDepositTransaction.TransactionId));
            }

            foreach (SupplyOrderItemEntity item in _supplyOrderItems)
            {
                //if (item.QuantityToBeAdded > 0 && item.NewShelfId > 0)
                if (item.QuantityToBeAdded > 0)
                {
                    List<TransactionItemEntity> transactionItems = (from t in transItems
                                                                    where t.RequestItemId == item.Id
                                                                    select t).ToList();

                    if (item.ShelvesBalances == null)
                    {
                        item.ShelvesBalances = LoadShelfBalances(transactionItems);
                    }

                    int index = 0;
                    //Loop for all shelves contain items 
                    foreach (ShelfBalance shelfBalance in item.ShelvesBalances)
                    {
                        
                        TransactionItemEntity transItem = new TransactionItemEntity();

                        if (transactionItems == null)
                        {

                            //item.DeliveredQuantity += item.QuantityToBeAdded;
                            item.DeliveredQuantity += (decimal)shelfBalance.Quantity;

                        }
                        else if (transactionItems.Count == 0)
                        {
                            item.DeliveredQuantity += (decimal)shelfBalance.Quantity;
                        }
                        else if (transactionItems.Count > 0)
                        {
                            if (transactionItems[index] != null)
                                transItem = transactionItems[index];
                            else
                                transItem = new TransactionItemEntity();

                            //item.DeliveredQuantity += (item.QuantityToBeAdded - transItem.Quantity);
                            item.DeliveredQuantity += ((decimal)shelfBalance.Quantity - transItem.Quantity);

                        }

                        item.LastDeliveryDate = AdditionDateDTP.Value.Date;


                        //transItem.ShelfId = item.NewShelfId;
                        transItem.ShelfId = shelfBalance.ShelfId;
                        transItem.StoreId = _currentDepositTransaction.Transaction.StoreId.Value;
                        transItem.ItemId = item.ItemId;
                        //transItem.Quantity = item.QuantityToBeAdded;
                        transItem.Quantity = (decimal)shelfBalance.Quantity;
                        transItem.RequestItemId = item.Id;
                        transItem.UnitPrice = item.UnitCost * _currentSupplyOrder.CurrencyRate;//item.SupplyOrder.CurrencyRate;//Business.GetItemCost(transItem.StoreId, transItem.ShelfId.Value, transItem.ItemId);

                        _currentDepositTransaction.Transaction.TransactionItems.Add(transItem);

                        index++;
                    }
                }
                else
                {
                    var q = (from t in transItems
                             where t.RequestItemId == item.Id
                             select t).FirstOrDefault();

                    if (q != null)
                    {
                        transItemsToDelete.Add(q);
                    }
                }
            }

            DALHelper.DeleteCollection(transItemsToDelete);

            _currentDepositTransaction.ExamRecordNumber = txtExamineDocSerial.Text;
            _currentDepositTransaction.ExamDate = ExamDateDTP.Value;

            if (DALHelper.SaveEntity(_currentDepositTransaction, true))
            {
                _currentSupplyOrder.IsProcessed = true;
                DALHelper.SaveEntity(_currentSupplyOrder);
                DALHelper.SaveCollection(_supplyOrderItems);

                using (var context = new ExtendedDataContext())
                {
                    var entity = context.ExamineDocs.Where(x => x.Serial == _currentDepositTransaction.ExamRecordNumber).
                        FirstOrDefault();

                    entity.IsUsedInDepositTransaction = true;

                    context.SubmitChanges();
                }

                RetrieveTransaction();
                MessageBox.Show("تم الحفظ بنجاح.");
            }
        }

        private List<ShelfBalance> LoadShelfBalances(List<TransactionItemEntity> transactionItems)
        {
            List<ShelfBalance> shelfbalances = new List<ShelfBalance>();
            foreach (TransactionItemEntity tie in transactionItems)
            {
                shelfbalances.Add(new ShelfBalance() { ShelfId = tie.ShelfId.Value, Quantity = (double)tie.Quantity });
            }
            return shelfbalances;
        }
        private void RetrieveBtn_Click(object sender, EventArgs e)
        {
            RetrieveTransaction();
            SyncSupplyItemsWithExamineItems();
        }


        private void RetrieveSupplyOrderBtn_Click(object sender, EventArgs e)
        {
            RetrieveSupplyOrder();
        }

        private void StoresDDL_SelectedIndexChanged(object sender, EventArgs e)
        {
            ResetTransactionItems();

                if (String.IsNullOrEmpty(ProjectsTB.Text))
                return;

            GetShelves();
        }
        
        private void PermitNumberTB_Leave(object sender, EventArgs e)
        {
            ValidatePermitNumber();
        }
        private void _tranItemsForm_RowValidating(int rowIndex, ref bool hasErrors)
        {
            //var remainderQuantityCell = _transItemsGrid.Rows[rowIndex].Cells[RemainderQuantity.Index];
            //var remainderQuantity = (remainderQuantityCell == null) ? 0 : remainderQuantityCell.Value;

            var examinQuantityCell = _transItemsGrid.Rows[rowIndex].Cells["columnExaminQuantity"];
            var examinQuantity = (examinQuantityCell == null) ? 0 : examinQuantityCell.Value;

            var quantityCell = _transItemsGrid.Rows[rowIndex].Cells[QuantityToBeAdded.Index];
            var quantity = quantityCell.Value;

            var DeliveredCell = _transItemsGrid.Rows[rowIndex].Cells["DeliveredQuantity"];
            var DeliveredQuantity = DeliveredCell.Value;

            if (quantity == null || examinQuantity == null)
                return;

            //if ((decimal)quantity > (decimal)examinQuantity - Decimal.Parse(DeliveredQuantity.ToString()))
           if ((decimal)quantity != (decimal)examinQuantity )
            {
                quantityCell.ErrorText = "الكمية المضافة يجب أن تساوي  الكمية المفحوصه من الطلب";
                hasErrors = true;
                return;
            }

            quantityCell.ErrorText = string.Empty;
        }


        private void InitializeDataSources()
        {
            _currentTransaction = new TransactionEntity();
            _currentDepositTransaction = new DepositTransactionEntity();
            _currentDepositTransaction.Transaction = _currentTransaction;

            BindDataSources();


            EnableDisableControls();
        }
        private void BindDataSources()
        {
            _TransBS.DataSource = _currentTransaction;
            _DepositBS.DataSource = _currentDepositTransaction;
        }
        private void LoadData()
        {

            DALHelper.FetchCollection(_depositTypes, null, null, new SortExpression(DepositTypeFields.Order | SortOperator.Ascending));
            DALHelper.FetchCollection(_inspectionStatus, null, null, new SortExpression(InspectionTypeFields.Order | SortOperator.Ascending));

            //FormsHelper.LoadComboBox(SupplierDDL, SupplierFields.Id, SupplierFields.Name, (x, y) => DALHelper.GetDynamicList(x, y, null));
           
            //FormsHelper.LoadComboBox(StoresDDL, StoreFields.Id, StoreFields.Name, () => Business.GetStoresForKeeper());

            

            StatusDDL.SelectedIndex = 0;
           // TypeDDL.SelectedIndex = 0;
            GetShelves();
            //SupplierDDL.SelectedIndex = 0;
        }
        private bool ValidateForm(bool ValidateGrid)
        {
            var isValid = true;

            var controls = new List<TextBox>();
            controls.Add(PermitNumberTB);
            controls.Add(PRNumberTB);
            controls.Add(PONumberTB);
            controls.Add(SupplyOrderNumberTB);
            controls.Add(txtExamineDocSerial);
            //controls.Add(BillOfLadingNmberTB);
            //controls.Add(PlateNumberTB);
            //controls.Add(DriverNameTB);

            if (_errorProviders == null)
            {
                _errorProviders = new List<ErrorProvider>();
            }
            else
            {
                foreach (var errorProvider in _errorProviders)
                {
                    errorProvider.Clear();
                    errorProvider.Dispose();
                }
            }
            foreach (var tb in controls)
            {
                if (string.IsNullOrEmpty(tb.Text.Trim()))
                {
                    var errorProvider = new ErrorProvider(this);
                    _errorProviders.Add(errorProvider);

                    errorProvider.SetError(tb, "يجب إدخال قيمة");
                    errorProvider.RightToLeft = true;

                    isValid = false;
                    continue;
                }
            }

            var combos = new List<ComboBox>();
            //combos.Add(StoresDDL);
            //combos.Add(TypeDDL);
            combos.Add(StatusDDL);

            foreach (var cmd in combos)
            {
                if (cmd.SelectedIndex < 0)
                {
                    var errorProvider = new ErrorProvider(this);
                    _errorProviders.Add(errorProvider);

                    errorProvider.SetError(cmd, "يجب إختيار قيمة");
                    errorProvider.RightToLeft = true;

                    isValid = false;
                }
            }

            if (GetSelectedStoreId() == 0)
            {
                var errorProvider = new ErrorProvider(this);
                _errorProviders.Add(errorProvider);

                errorProvider.SetError(StoresTB, "يجب إدخال قيمة صحيحة ");
                errorProvider.RightToLeft = true;

                isValid = false;

            }

            if (ValidateGrid)
            {
                if (!ValidatePermitNumber())
                    isValid = false;
            }

            if (!_tranItemsForm.IsDataValid())
                isValid = false;

            _tranItemsForm.ValidateCollection();

            if (_supplyOrderItems.Count <= 0)
            {
                isValid = false;
                MessageBox.Show("يجب إضافة أصناف", "خطأ فى الحفظ", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return isValid;
        }
        private bool ValidatePermitNumber()
        {
            return FormsHelper.ValidatePermitNumber(this, PermitNumberTB, _errorProviders, "Deposit", _currentTransaction.Id);
        }
        private void GetShelves()
        {
            var storeId = GetSelectedStoreId();
            _shelves.Clear();
            DALHelper.FetchCollection(_shelves, new RelationPredicateBucket(ShelfFields.StoreId == storeId));
        }
        private void ResetTransactionItems()
        {
            //if (_tranItemsForm != null)
            //{
            //    _tranItemsForm.Dispose();
            //    _tranItemsForm = null;
            //}

            //var label = new Label();
            //_tranItemsForm = new DataMngrFormBase<TransactionItemEntity>(_supplyOrderItems, _transItemsGrid, _itemsBS, new Button(), label, label, new RelationPredicateBucket(TransactionItemFields.TransactionId == 0));
            //_tranItemsForm.SetNumericFields(new List<int> { 3 });
            //_tranItemsForm.SetMandatoryFields(new List<int>() { 0, 1, 3 });
        }
        private int GetSelectedStoreId()
        {
            DataTable DTStore = Business.GetStoreDetails(StoresTB.Text);
            if (DTStore.Rows.Count > 0)
            {
                return Int32.Parse(DTStore.Rows[0][0].ToString());
            }

            return 0;
          
        }
        private void RetrieveTransaction()
        {
            if (string.IsNullOrEmpty(PermitNumberTB.Text.Trim()))
                return;

            var collection = new EntityCollection<TransactionEntity>();
            var prefetch = new PrefetchPath2(EntityType.TransactionEntity);
            prefetch.Add(TransactionEntity.PrefetchPathDepositTransactions);

            var filter = new RelationPredicateBucket(TransactionFields.Type == "Deposit");
            filter.PredicateExpression.Add(TransactionFields.PermitNumber == PermitNumberTB.Text.Trim());

            //Added by Thabet 
            //retrieve only the all deposit transaction that bind with supply order (if its filled) 
            if (!string.IsNullOrEmpty(SupplyOrderNumberTB.Text))
            {
                filter.PredicateExpression.Add(new PredicateExpression(DepositTransactionFields.SupplyOrderNumber == SupplyOrderNumberTB.Text));
            }

            var supplyOrderRelations = new RelationCollection();
            supplyOrderRelations.Add(SupplyOrderEntity.Relations.ProjectEntityUsingProjectId);

            filter.Relations.Add(TransactionEntity.Relations.DepositTransactionEntityUsingTransactionId);
            filter.PredicateExpression.Add(
                new FieldCompareSetPredicate(DepositTransactionFields.SupplyOrderNumber, null, SupplyOrderFields.SupplyOrderNumber, null, SetOperator.In,
                    new PredicateExpression(ProjectFields.IsGeneral == true), supplyOrderRelations));

            DALHelper.FetchCollection(collection, filter, prefetch);

            if (collection.Count <= 0 || collection[0].DepositTransactions.Count <= 0)
            {
                ResetForm();
            }
            else
            {
                _currentTransaction = collection[0];
                _currentDepositTransaction = _currentTransaction.DepositTransactions[0];

                RetrieveSupplyOrder(_currentDepositTransaction.SupplyOrderNumber);

                var storefilter = new RelationPredicateBucket(StoreFields.Id == collection[0].StoreId);
                EntityCollection<StoreEntity> Store = new EntityCollection<StoreEntity>();
                DALHelper.FetchCollection(Store, storefilter);
                StoresTB.Text = Store[0].Code;

                //var supplierCollection = new EntityCollection<SupplierEntity>();
                //var supplierFilter = new RelationPredicateBucket(SupplierFields.Id == _currentDepositTransaction.SupplierId);
                //DALHelper.FetchCollection(supplierCollection, supplierFilter);
                //SupplierTB.Text = supplierCollection[0].Code;

                BindDataSources();

                // Assign examine //
                txtExamineDocSerial.Text = _currentDepositTransaction.ExamRecordNumber;
                ExamDateDTP.Value = _currentDepositTransaction.ExamDate.HasValue
                                        ? _currentDepositTransaction.ExamDate.Value
                                        : DateTime.Now;
                ///////////////////
                var transItems = new EntityCollection<TransactionItemEntity>();
                DALHelper.FetchCollection(transItems, new RelationPredicateBucket(TransactionItemFields.TransactionId == _currentDepositTransaction.TransactionId));
                foreach (SupplyOrderItemEntity orderItem in _supplyOrderItems)
                {
                    List<TransactionItemEntity> transactionItems = (from t in transItems
                                                                    where t.ItemId == orderItem.ItemId && t.RequestItemId == orderItem.Id
                                                                    select t).ToList();


                    if (transactionItems == null)
                        continue;

                    //orderItem.NewShelfId = q.ShelfId.Value;
                    orderItem.QuantityToBeAdded = transactionItems.Sum(t => t.Quantity);



                    if (orderItem.ShelvesBalances == null)
                    {
                        orderItem.ShelvesBalances = LoadShelfBalances(transactionItems);
                    }

                }


                

            }

            //Fill ItemName & ItemCode columns in retrieving transaction 
            if (_transItemsGrid.Rows.Count > 0)
            {
                for (int currentRow = 0; currentRow < _transItemsGrid.Rows.Count - 1; currentRow++)
                {
                    _transItemsGrid.Rows[currentRow].Cells[SequenceColumn.Index].Value = currentRow + 1;

                    int productItemId = Int32.Parse(_transItemsGrid.Rows[currentRow].Cells[ItemIdColumn.Index].Value.ToString());
                    GetItemDetailsByItemId(currentRow, productItemId);
                }

            }

            ValidatePermitNumber();

            EnableDisableControls();
        }
        private void EnableDisableControls()
        {
            if (_currentDepositTransaction.TransactionStatus == 1)
            {
                _alreadyPricedLbl.Text = "* إذن الإضافه تم حفظه نهائيا ويمكن تسعيره فقط  !";
            }
            else if (_currentDepositTransaction.TransactionStatus == 2)
            {
                _alreadyPricedLbl.Text = "* إذن الإضافه تم تسعيره و لا يمكن تغيير بياناته !";
            }
            else
            {
                _alreadyPricedLbl.Text = String.Empty;
            }

            var valid = (!_currentDepositTransaction.IsPriced) && (_currentSupplyOrder != null) && (!_currentSupplyOrder.IsNew);
            var isSubmitted = _currentDepositTransaction.TransactionStatus > 0;

            var isEditable = !((!valid) || isSubmitted);

            _transItemsGrid.Enabled = isEditable;// valid;
            SaveBtn.Enabled = isEditable;// valid;
            btnSubmit.Enabled = isEditable;

            bindingNavigator1.Enabled = isEditable;// valid;
            _alreadyPricedLbl.Visible = !isEditable;// valid;

            StoresTB.Enabled = _currentTransaction.IsNew;
            ProjectsTB.Enabled = _currentTransaction.IsNew;
            NewBtn.Enabled = !_currentTransaction.IsNew;
            DeleteBtn.Enabled = !_currentTransaction.IsNew && isEditable; //!(_currentTransaction.IsNew || _currentDepositTransaction.IsPriced);
        }

        private void RetrieveSupplyOrder()
        {
            var supplyOrderNumer = SupplyOrderNumberTB.Text;
            ResetForm();
            RetrieveSupplyOrder(supplyOrderNumer);
            EnableDisableControls();



            //Fill ItemName & ItemCode columns in retrieving transaction 
            if (_transItemsGrid.Rows.Count > 0)
            {
                for (int currentRow = 0; currentRow < _transItemsGrid.Rows.Count - 1; currentRow++)
                {
                    _transItemsGrid.Rows[currentRow].Cells[SequenceColumn.Index].Value = currentRow + 1;

                    int productItemId = Int32.Parse(_transItemsGrid.Rows[currentRow].Cells[ItemIdColumn.Index].Value.ToString());
                    GetItemDetailsByItemId(currentRow, productItemId);


                }

            }
        }

        private void RetrieveSupplyOrder(string supplyOrderNumber)
        {
            if (string.IsNullOrEmpty(supplyOrderNumber.Trim()))
                return;

            var collection = new EntityCollection<SupplyOrderEntity>();

            var filter = new RelationPredicateBucket(SupplyOrderFields.SupplyOrderNumber == supplyOrderNumber.Trim());
            filter.PredicateExpression.Add(ProjectFields.IsGeneral == true);
            filter.Relations.Add(SupplyOrderEntity.Relations.ProjectEntityUsingProjectId);

            DALHelper.FetchCollection(collection, filter);

            if (collection.Count <= 0)
            {

                _currentSupplyOrder = new SupplyOrderEntity();
                _SupplyOrderBS.DataSource = _currentSupplyOrder;
            }
            else
            {
                var projectfilter = new RelationPredicateBucket(ProjectFields.Id == collection[0].ProjectId);
                EntityCollection<ProjectEntity> project = new EntityCollection<ProjectEntity>();
                DALHelper.FetchCollection(project, projectfilter);
                ProjectsTB.Text = project[0].Code;

                var supplierCollection = new EntityCollection<SupplierEntity>();
                var supplierFilter = new RelationPredicateBucket(SupplierFields.Id == collection[0].SupplierId);
                DALHelper.FetchCollection(supplierCollection, supplierFilter);
                //SupplierTB.Text = supplierCollection[0].Code;
                lblSupplier.Text = Business.GetSupplierDetails(supplierCollection[0].Code).Rows[0]["Name"].ToString();

                _currentSupplyOrder = collection[0];
                _SupplyOrderBS.DataSource = _currentSupplyOrder;
            }
            //_requestItems.Clear();
            //DALHelper.FetchCollection(_requestItems, new RelationPredicateBucket(WithdrawRequestItemFields.WithdrawRequestId == _currentRequest.Id));			
            LoadSupplyOrderItems(_currentSupplyOrder.Id);
            //EnableDisableControls();
        }
        private void LoadSupplyOrderItems(int supplyOrderId)
        {
            if (_tranItemsForm != null)
            {
                _tranItemsForm.Dispose();
                _tranItemsForm = null;
            }

            var prefetch = new PrefetchPath2(EntityType.SupplyOrderItemEntity);
            prefetch.Add(SupplyOrderItemEntity.PrefetchPathItem).SubPath.Add(ItemEntity.PrefetchPathUnit_);

            var label = new Label();
            _tranItemsForm = new DataMngrFormBase<SupplyOrderItemEntity>(_supplyOrderItems, _transItemsGrid, _SupplyOrderItemsBS, new Button(), label, label, new RelationPredicateBucket(SupplyOrderItemFields.SupplyOrderId == supplyOrderId), prefetch);
            _tranItemsForm.SetNumericFields(new List<int> { QuantityToBeAdded.Index });
            _tranItemsForm.SetMandatoryFields(new List<int>() {  QuantityToBeAdded.Index });
            _tranItemsForm.RowValidating += new DataMngrFormBase<SupplyOrderItemEntity>.RaiseRowValidating(_tranItemsForm_RowValidating);
        }
        private void ResetForm()
        {
            _currentSupplyOrder = new SupplyOrderEntity();
            _currentDepositTransaction = new DepositTransactionEntity();
            _currentDepositTransaction.Transaction = new TransactionEntity();
            _supplyOrderItems.Clear();

           // SupplierTB.Text = "";
            lblSupplier.Text = string.Empty;
            ProjectsTB.Text = "";
            StoresTB.Text = "";
            //txtExamineDocSerial.Text = string.Empty;

            _DepositBS.DataSource = _currentDepositTransaction;
            _TransBS.DataSource = _currentDepositTransaction.Transaction;
            _SupplyOrderBS.DataSource = _currentSupplyOrder;

            _currentTransaction = new TransactionEntity();

            EnableDisableControls();
        }

        private void _transItemsGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			
            //Open the search form for products using code or name 
            if (e.ColumnIndex == ItemCodeColumn.Index)
            {
                 var itemPickerForm = new ItemPickerForm(1);
                 if (itemPickerForm.ShowDialog() == DialogResult.OK)
                {
                    GetItemDetailsByItemId(e.RowIndex, itemPickerForm.SelectedItemId);
                                     
                }
            }

             else if (e.ColumnIndex == QuantityToBeAdded.Index)
             {

                 if (!ValidateForm(false))
                 {

                     return;
                 }
                 

                 //double availableBalance=Double.Parse(_transItemsGrid.Rows[e.RowIndex].Cells[RemainderQuantity.Index].Value.ToString());
                 double availableBalance = 0;
                 int itemId=Int32.Parse(_transItemsGrid.Rows[e.RowIndex].Cells[ItemIdColumn.Index].Value.ToString());

                 

                 if (_transItemsGrid.Rows[e.RowIndex].Cells[QuantityToBeAdded.Index].Value.ToString() == "0")
                 {

                     ShelfBalanceForm shelfBalanceFrm = new ShelfBalanceForm(GetSelectedStoreId(), itemId, availableBalance, _currentTransaction.Id);
                     shelfBalanceFrm.ShowDialog();


                     _transItemsGrid.Rows[e.RowIndex].Cells[QuantityToBeAdded.Index].Value = shelfBalanceFrm.allItemsShelvesBalancesValue.ToString();

                     ((SupplyOrderItemEntity)_supplyOrderItems[e.RowIndex]).ShelvesBalances = shelfBalanceFrm.ItemShelvesBalances;
                 }
                 else
                 {
                     ShelfBalanceForm shelfBalanceFrm = new ShelfBalanceForm(((SupplyOrderItemEntity)_supplyOrderItems[e.RowIndex]).ShelvesBalances, availableBalance, GetSelectedStoreId());
                     shelfBalanceFrm.ShowDialog();
                     
                     _transItemsGrid.Rows[e.RowIndex].Cells[QuantityToBeAdded.Index].Value = shelfBalanceFrm.allItemsShelvesBalancesValue.ToString();

                     ((SupplyOrderItemEntity)_supplyOrderItems[e.RowIndex]).ShelvesBalances = shelfBalanceFrm.ItemShelvesBalances;
                 }

                //_transItemsGrid.Rows[e.RowIndex].Cells[Weight.Index].Value=
                 //if(_transItemsGrid.Rows[e.RowIndex].Cells[QuantityToBeAdded.Index].Value!=null)
                 //{
                 //    decimal qty =
                 //        decimal.Parse(_transItemsGrid.Rows[e.RowIndex].Cells[QuantityToBeAdded.Index].Value.ToString());

                 //    var itemCollection = new EntityCollection<ItemEntity>();

                 //    var itmId = ((SupplyOrderItemEntity) (_supplyOrderItems[e.RowIndex])).ItemId;

                 //    var itemFilter = new RelationPredicateBucket(ItemFields.Id == itmId);

                 //    DALHelper.FetchCollection(itemCollection, itemFilter);

                 //    if (itemCollection.Count > 0)
                 //    {
                 //        _transItemsGrid.Rows[e.RowIndex].Cells[Weight.Index].Value = itemCollection[0].Weight*
                 //                                                                     qty;
                         
                 //    }
                 //}
                 _transItemsGrid.Refresh();
                 SyncSupplyItemsWithExamineItems();
                 //var itemIdValue = _transItemsGrid.Rows[e.RowIndex].Cells[ItemIdColumn.Index].Value;
                 //if (itemIdValue == null)
                 //    return;

                 //var unitConverterForm = new UnitConverterForm((int)itemIdValue);
                 //if (unitConverterForm.ShowDialog() == DialogResult.OK)
                 //{
                 //    _transItemsGrid.SuspendLayout();
                 //    _transItemsGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = unitConverterForm.Value;
                 //    _transItemsGrid.UpdateCellValue(e.ColumnIndex, e.RowIndex);
                 //    _transItemsGrid.ResumeLayout(true);
                 //}
             }
            
		}

        private void SearchBtn_Click(object sender, EventArgs e)
        {
            var supplyOrderRelations = new RelationCollection();
            supplyOrderRelations.Add(SupplyOrderEntity.Relations.ProjectEntityUsingProjectId);

            var filter = new RelationPredicateBucket(TransactionFields.Type == "Deposit");

            //Added by Thabet 
            //retrieve only the all deposit transaction that bind with supply order (if its filled) 
            if (!string.IsNullOrEmpty(SupplyOrderNumberTB.Text))
            {
                filter.PredicateExpression.Add(new PredicateExpression(DepositTransactionFields.SupplyOrderNumber == SupplyOrderNumberTB.Text));
            }

            filter.Relations.Add(TransactionEntity.Relations.ProjectEntityUsingProjectId);
            filter.Relations.Add(TransactionEntity.Relations.DepositTransactionEntityUsingTransactionId);
            filter.PredicateExpression.Add(
                new FieldCompareSetPredicate(DepositTransactionFields.SupplyOrderNumber, null, SupplyOrderFields.SupplyOrderNumber, null, SetOperator.In,
                    new PredicateExpression(ProjectFields.IsGeneral == true), supplyOrderRelations));


            var searchForm = new SearchForm(TransactionFields.PermitNumber, TransactionFields.ProjectId, TransactionFields.Date, filter, () => Business.GetGeneralProjects());
            if (searchForm.ShowDialog() == DialogResult.OK)
            {
                PermitNumberTB.Text = searchForm.SelectedNumber;
                RetrieveTransaction();
                SyncSupplyItemsWithExamineItems();
            }
        }

        private void SearchSupplyOrderBtn_Click(object sender, EventArgs e)
        {
            var filter = new RelationPredicateBucket();
            filter.Relations.Add(SupplyOrderEntity.Relations.ProjectEntityUsingProjectId);
            filter.PredicateExpression.Add(ProjectFields.IsGeneral == true);

            var searchForm = new SearchSupplyOrderForm(SupplyOrderFields.SupplyOrderNumber, SupplyOrderFields.ProjectId, SupplyOrderFields.Date, filter, () => Business.GetGeneralProjects());
            if (searchForm.ShowDialog() == DialogResult.OK)
            {
                SupplyOrderNumberTB.Text = searchForm.SelectedNumber;
                RetrieveSupplyOrder();
                SyncSupplyItemsWithExamineItems();
            }
        }

        private void DeleteBtn_Click(object sender, EventArgs e)
        {
            var form = new DeleteConfirmationForm();

            if (form.ShowDialog() == DialogResult.Yes)
            {
                if (DALHelper.DeleteEntity(_currentTransaction))
                {
                    ResetForm();
                }
            }
        }

        /// <summary>
        /// Retrieve the data table represent item(Product) details based on ItemId
        /// Added by Thabet
        /// </summary>
        /// <param name="rowIndex"> Index of row in data grid</param>
        /// <param name="itemId">The ID of item(Product)</param>
        private void GetItemDetailsByItemId(int rowIndex, int itemId)
        {
            DataTable itemDT = Business.GetItemDetails(itemId);
            if (itemDT.Rows.Count <= 0)
                return;

            _transItemsGrid.Rows[rowIndex].Cells[ItemCodeColumn.Index].Value = itemDT.Rows[0][0].ToString();
            _transItemsGrid.Rows[rowIndex].Cells[ItemNameColumn.Index].Value = itemDT.Rows[0][1].ToString();

            _transItemsGrid.Rows[rowIndex].Cells[ItemIdColumn.Index].Value = itemId;

            return;
        }
        /// <summary>
        /// Retrieve the data table represent item(Product) details based on ItemCode
        /// Added by Thabet
        /// </summary>
        /// <param name="rowIndex">Index of row in data grid</param>
        /// <param name="itemCode">The code of item</param>
        private void GetItemDetailsByItemCode(int rowIndex, string itemCode)
        {
            var dt = Business.GetItemDetails(itemCode, 1);
            if (dt.Rows.Count <= 0)
                return;

            _transItemsGrid.Rows[rowIndex].Cells[ItemIdColumn.Index].Value = dt.Rows[0][0].ToString();
            _transItemsGrid.Rows[rowIndex].Cells[ItemNameColumn.Index].Value = dt.Rows[0][1].ToString();

            return;
        }

        private void _transItemsGrid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;

            if ((e.ColumnIndex == ItemCodeColumn.Index) && (_transItemsGrid.Rows[e.RowIndex].Cells[ItemCodeColumn.Index].Value != null))
            {
                string productItemCode = _transItemsGrid.Rows[e.RowIndex].Cells[ItemCodeColumn.Index].Value.ToString();
                GetItemDetailsByItemCode(e.RowIndex, productItemCode);
            }

        }

        private void _transItemsGrid_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            _transItemsGrid.Rows[e.RowIndex].Cells[SequenceColumn.Index].Value = e.RowIndex + 1;
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!ValidateForm(true))
                return;
           
            var form = new SaveConfirmationForm();

            if (form.ShowDialog() == DialogResult.Yes)
            {
                _currentDepositTransaction.TransactionStatus = 1;
                Save();
                Business.StoreItems(GetSelectedStoreId(), _currentDepositTransaction, _currentTransaction);
            }

            SyncSupplyItemsWithExamineItems();


        }

        /// <summary>
        /// When click search examine form, search for it and load its supply order
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearchExamineDoc_Click(object sender, EventArgs e)
        {
            SearchExamineDoc searchForm = _currentSupplyOrder == null
                                       ? new SearchExamineDoc()
                                       : new SearchExamineDoc(_currentSupplyOrder.Id, false);

            if (searchForm.ShowDialog() == DialogResult.OK)
            {
                // the serial of the examination document
                txtExamineDocSerial.Text = searchForm.SelectedNumber;
                PopulteExaminOrder(txtExamineDocSerial.Text);

                //var examine = Business.GetExamineBySerial(searchForm.SelectedNumber);
                //ExamDateDTP.Value = examine.CreationDate;
                //ExamDateDTP.Enabled = false;

                //// Get supply if Examination was chosen
                //SupplyOrderEntity supplyOrderEntity = Business.GetSupplyOrderByIdOrNumber
                //    (id: searchForm.SelectedSupplyOrderId);

                //if (supplyOrderEntity != null)
                //{
                //    SupplyOrderNumberTB.Text = supplyOrderEntity.SupplyOrderNumber;
                //    RetrieveSupplyOrder();
                //    // Use this method to replace supply order Qty with Examine Qty
                //    SyncSupplyItemsWithExamineItems();
                //}
                //else
                //{
                //    SupplyOrderNumberTB.Text = string.Empty;
                //}
            }
        }
        
        /// <summary>
        /// Get Qty from examine and assign it to the supply as per Khaled confirmation
        /// </summary>
        /// <param name="examine"></param>
        private void SyncSupplyItemsWithExamineItems()
        {
            ExamineDoc examine = Business.GetExamineBySerial(txtExamineDocSerial.Text);

            if(examine == null)
             return;

            int count = 0;


            List<SupplyOrderItemEntity> deletedSupplOrderItems = new List<SupplyOrderItemEntity>();
            foreach (SupplyOrderItemEntity supplyOrderItem in _supplyOrderItems)
            {
                var examineDocItem =
                    examine.ExamineDocItems.Where(x => x.ItemId == supplyOrderItem.ItemId).FirstOrDefault();

                _transItemsGrid.Rows[count].Cells[columnExaminQuantity.Index].Value = examineDocItem != null ? examineDocItem.Quantity : supplyOrderItem.Quantity;

                if (examineDocItem == null)
                {
                    deletedSupplOrderItems.Add(supplyOrderItem);
                }
                else if (examineDocItem.Quantity == 0)
                {
                    deletedSupplOrderItems.Add(supplyOrderItem);
                }

               
                //Just work around to remove delivered quantity that not bind to the current examin doc
                if ((supplyOrderItem.DeliveredQuantity != 0) && (examineDocItem.Quantity == 0))
                {
                    _transItemsGrid.Rows[count].Cells[DeliveredQuantity.Index].Value = (decimal)0.00000;
                }
                else
                {
                    _transItemsGrid.Rows[count].Cells[DeliveredQuantity.Index].Value = supplyOrderItem.DeliveredQuantity;
                }

                count++;
            }

            //Remove supplyOrderItems
            foreach(SupplyOrderItemEntity soi in deletedSupplOrderItems)
            {
                _supplyOrderItems.Remove(soi);
            }

           

            if (examine.IsAccepted.Value)
            {
                StatusDDL.SelectedIndex = 0;
            }
            else
            {
                StatusDDL.SelectedIndex = 3;
            }
            //for (int i = 0; i < _transItemsGrid.Rows.Count - 1; i++)
            //{
            //    _transItemsGrid.Rows[i].Cells[RemainderQuantity.Index].Value = examine.ExamineDocItems[i].Quantity;
            //}

           _transItemsGrid.Refresh();
        }

        private void SearchProjectBtn_Click(object sender, EventArgs e)
        {
            ResetTransactionItems();
            var filter = new RelationPredicateBucket();
            filter.PredicateExpression.Add(ProjectFields.IsGeneral == true);
            var searchForm = new SearchForm(ProjectFields.Code, ProjectFields.Name, ProjectFields.ActualStartDate, filter,
                                            () => Business.GetGeneralProjects());
            if (searchForm.ShowDialog() == DialogResult.OK)
            {
                ProjectsTB.Text = searchForm.SelectedNumber;

                EnableDisableControls();
            }

        }

        private void ProjectsTB_TextChanged(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(ProjectsTB.Text))
            {
                ProjectEntity project = Business.GetProjectByCode(ProjectsTB.Text);

                if (project != null)
                {
                    lblProjectName.Text = project.Name;
                    EnableDisableControls();
                    Business.GetSupplyOrderItemsPlannedForProject(project.Id, _items);

                    var filter = new RelationPredicateBucket();
                    filter.PredicateExpression.Add(new FieldCompareSetPredicate(ContractorFields.Id, null, ProjectContractorFields.ContractorId, null, SetOperator.In, new PredicateExpression(ProjectContractorFields.ProjectId == project.Id)));

                    ResetTransactionItems();

                    EnableDisableControls();
                }
                else
                {
                    lblProjectName.Text = string.Empty;
                }

                
            }
            else
            {
                lblProjectName.Text = string.Empty;
                //RunBtn.Enabled = false;
            }
        }

        private void StoresTB_TextChanged(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(StoresTB.Text))
            {
                DataTable DTStore = Business.GetStoreDetails(StoresTB.Text);
                if (DTStore.Rows.Count > 0)
                {
                    lblStoreName.Text = DTStore.Rows[0][2].ToString();
                    EnableDisableControls();
                }
                else
                {
                    lblStoreName.Text = string.Empty;
                    //RunBtn.Enabled = false;
                }
            }
            else
            {
                lblStoreName.Text = string.Empty;
                //RunBtn.Enabled = false;
            }
        }

        private void SearchStoresBtn_Click(object sender, EventArgs e)
        {
            var searchForm = new fromGeneralEntityPicker("Store");
            if (searchForm.ShowDialog() == DialogResult.OK)
            {
                StoresTB.Text = searchForm.SelectedItemCode;

            }
        }

        

        private void btnRetriveExaminOrder_Click(object sender, EventArgs e)
        {
            // the serial of the examination document
            //txtExamineDocSerial.Text = searchForm.SelectedNumber;

            PopulteExaminOrder(txtExamineDocSerial.Text);

        }

        private void PopulteExaminOrder(string ExaminOrderSerial)
        {
            var examine = Business.GetExamineBySerial(ExaminOrderSerial);

            if (examine == null)
            {
                var errorProvider = new ErrorProvider(this);
                errorProvider.SetError(txtExamineDocSerial, "محضر الفحص غير موجود");
                return;
            }

            ExamDateDTP.Value = examine.CreationDate;
            ExamDateDTP.Enabled = false;

            // Get supply if Examination was chosen
            SupplyOrderEntity supplyOrderEntity = Business.GetSupplyOrderByIdOrNumber(examine.SupplyOrderId.Value);

            if (supplyOrderEntity != null)
            {
                SupplyOrderNumberTB.Text = supplyOrderEntity.SupplyOrderNumber;
                RetrieveSupplyOrder();
                // Use this method to replace supply order Qty with Examine Qty
                SyncSupplyItemsWithExamineItems();
            }
            else
            {
                SupplyOrderNumberTB.Text = string.Empty;
            }
        }
    }
}
